var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/businessComponent/Attachment/util.ts
var util_exports = {};
__export(util_exports, {
  asyncPool: () => asyncPool,
  customRequest: () => customRequest,
  downloadFile: () => downloadFile,
  getFileCenterApiUrl: () => getFileCenterApiUrl,
  getFileMd5: () => getFileMd5,
  getFileMd5BySlice: () => getFileMd5BySlice,
  getFileSize: () => getFileSize,
  getFileType: () => getFileType,
  getSortNumArr: () => getSortNumArr,
  isJingeOpen: () => isJingeOpen,
  openTab: () => openTab
});
module.exports = __toCommonJS(util_exports);
var import_spark_md5 = __toESM(require("spark-md5"));
var import_functionalComponent = require("../../functionalComponent");
var import_util = require("../../util");
var requestTypeList = ["get", "post", "body"];
var requestFactory = (type) => async (option) => {
  const res = await import_util.iup.request[type](option);
  if ((res == null ? void 0 : res.code) === 0) {
    return {
      ...res,
      success: true
    };
  } else {
    import_functionalComponent.message.error((res == null ? void 0 : res.message) ?? "未知错误");
    return {
      ...res,
      success: false
    };
  }
};
var customRequest = requestTypeList.reduce(
  (value, item) => ({ ...value, [item]: requestFactory(item) }),
  {}
);
var openTab = (title = "文件预览", url, params = {}) => {
  const targetUrl = import_util.iup.handleUrl(url, params);
  window.open(url, "_blank", "noopener,noreferrer");
};
var downloadFile = (filename, blob, type = "blob") => {
  const element = document.createElement("a");
  element.download = filename;
  element.href = type === "url" ? blob : URL.createObjectURL(blob);
  element.click();
};
var getFileSize = (size) => {
  if (size === null || Number.isNaN(+size))
    return size;
  const num = 1024;
  const unitMap = ["B", "KB", "MB", "GB"];
  size = +size;
  for (let i = 0; i < 4; i++) {
    if (size < Math.pow(num, i + 1))
      return `${(size / Math.pow(num, i)).toFixed(2)}${unitMap[i]}`;
  }
  return `${(size / Math.pow(num, 4)).toFixed(2)}TB`;
};
var isJingeOpen = (fileType, showControl) => {
  if (["doc", "docx", "xls", "xlsx"].includes(fileType) && showControl !== 0) {
    if (showControl === 1 && ["doc", "docx"].includes(fileType) || showControl === 2 && ["xls", "xlsx"].includes(fileType) || showControl === 3) {
      return true;
    }
  }
  return false;
};
var getFileType = (fileName) => {
  var _a;
  return (_a = fileName == null ? void 0 : fileName.split(".").slice(-1)[0]) == null ? void 0 : _a.toLowerCase();
};
var getFileMd5 = (file) => new Promise((resolve) => {
  const fileReader = new FileReader();
  const spark = new import_spark_md5.default.ArrayBuffer();
  fileReader.onload = (e) => {
    var _a;
    spark.append((_a = e.target) == null ? void 0 : _a.result);
    resolve(spark.end());
  };
  fileReader.readAsArrayBuffer(file);
});
var getFileMd5BySlice = (file, chunkSize = 1024 * 1024 * 5) => {
  if (!file) {
    return Promise.reject("文件不存在");
  }
  const chunks = Math.ceil(file.size / chunkSize);
  if (chunks < 5) {
    return getFileMd5(file);
  }
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader();
    const spark = new import_spark_md5.default.ArrayBuffer();
    let currentChunk = 0;
    const loadNext = () => {
      fileReader.readAsArrayBuffer(
        File.prototype.slice.call(file, currentChunk * chunkSize, Math.min((currentChunk + 1) * chunkSize, file.size))
      );
    };
    fileReader.onload = function(e) {
      var _a;
      spark.append((_a = e.target) == null ? void 0 : _a.result);
      currentChunk++;
      if (currentChunk < chunks) {
        loadNext();
      } else {
        resolve(spark.end());
      }
    };
    fileReader.onerror = function(error) {
      reject(error);
    };
    loadNext();
  });
};
function getSortNumArr(num = 10) {
  let arr = [];
  for (let i = 0; i < num; i++) {
    arr.push(i + 1);
  }
  return arr;
}
async function asyncPool(array, limit, iteratorFn) {
  const ret = [];
  const executing = [];
  for (const item of array) {
    const p = Promise.resolve().then(() => iteratorFn(item, array));
    ret.push(p);
    if (limit <= array.length) {
      const e = p.then(() => executing.splice(executing.indexOf(e), 1));
      executing.push(e);
      if (executing.length >= limit) {
        await Promise.race(executing);
      }
    }
  }
  return Promise.all(ret);
}
function getFileCenterApiUrl(relativeUrl) {
  const { fileUrl } = import_util.iup.getUser();
  if (fileUrl && !fileUrl.startsWith("http")) {
    import_functionalComponent.message.warn(`目前文件中心配置地址为相对地址（${fileUrl}），绝对地址请以 http(s) 开头`);
  }
  return {
    absUrl: fileUrl ? true : false,
    url: fileUrl ? `${fileUrl}${relativeUrl}` : relativeUrl
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  asyncPool,
  customRequest,
  downloadFile,
  getFileCenterApiUrl,
  getFileMd5,
  getFileMd5BySlice,
  getFileSize,
  getFileType,
  getSortNumArr,
  isJingeOpen,
  openTab
});
